package com.dream;

import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;

@SpringBootConfiguration
public class MybatisConfig {
	
	@Bean
	@ConditionalOnMissingBean//当容器里没有SqlSessionFactoryBean的情况下创建该对象
	public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSource ds) {
		
		MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(ds);
		
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource mybatisConfigXml = resolver.getResource("classpath:mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);

		//给实体类起别名
		sqlSessionFactoryBean.setTypeAliasesPackage("com.dream.bean");
		return sqlSessionFactoryBean;
	}

}
